package com.woniuxy.sales.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.sales.config.AlipayConfig;
import com.woniuxy.sales.mapper.ProductsMapper;
import com.woniuxy.sales.mapper.ProductsOrdersDetailsMapper;
import com.woniuxy.sales.model.entity.Products;
import com.woniuxy.sales.model.entity.ProductsOrders;
import com.woniuxy.sales.model.entity.ProductsOrdersDetails;
import com.woniuxy.sales.model.vo.ProductsOrderVo;
import com.woniuxy.sales.service.ProductsOrdersService;
import com.woniuxy.sales.mapper.ProductsOrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author liboyang
* @description 针对表【products_orders】的数据库操作Service实现
* @createDate 2024-11-08 14:45:33
*/
@Service
@Slf4j
public class ProductsOrdersServiceImpl extends ServiceImpl<ProductsOrdersMapper, ProductsOrders>
    implements ProductsOrdersService{
    @Autowired
    private ProductsOrdersMapper productsOrdersMapper;
    @Autowired
    private ProductsOrdersDetailsMapper productsOrdersDetailsMapper;
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AlipayConfig alipayConfig;
    @Autowired
    private ProductsMapper productsMapper;

    @Override
    @Transactional
    public ProductsOrderVo addOrder(Integer userId, ProductsOrderVo order) {
        // 生成订单ID（雪花算法）
        Long orderId = IdUtil.getSnowflake(1, 1).nextId();
        // 创建并设置 ProductsOrders 实体
        ProductsOrders productsOrders = new ProductsOrders();
        productsOrders.setId(orderId);
        productsOrders.setProductId(order.getProductId());
        productsOrders.setUserId(userId);
        productsOrders.setName(order.getName());
        productsOrders.setTelephone(order.getTelephone());
        productsOrders.setPrice(order.getPrice());
        productsOrders.setStatus(order.getStatus());
        productsOrders.setAddress(order.getAddress());
        productsOrders.setCreatedTime(new Date());
        // 插入订单数据
        productsOrdersMapper.insert(productsOrders);
        // 创建并设置 ProductsOrdersDetails 实体
        ProductsOrdersDetails productsOrdersDetails = new ProductsOrdersDetails();
        productsOrdersDetails.setCarPrice(order.getCarPrice());
        productsOrdersDetails.setCarColor(order.getCarColor());
        productsOrdersDetails.setCarSeat(order.getCarSeat());
        productsOrdersDetails.setCarWheel(order.getCarWheel());
        productsOrdersDetails.setProductsOrdersId(orderId);
        productsOrdersDetails.setImgs(order.getImgs());
        // 插入订单详情数据
        productsOrdersDetailsMapper.insert(productsOrdersDetails);
        // 设置返回的 ProductsOrderVo 对象
        order.setId(orderId);  // 设置生成的订单ID
        order.setProductsOrdersId(orderId);  // 设置生成的订单编号
        return order;  // 返回包含订单ID的 ProductsOrderVo
    }


    @Override
    public List<ProductsOrders> queryOrder(Integer userId, Integer status) {
        LambdaQueryWrapper<ProductsOrders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductsOrders::getUserId, userId);

        if (status == 0) {
            wrapper.orderByDesc(ProductsOrders::getCreatedTime);
            List<ProductsOrders> orders = productsOrdersMapper.selectList(wrapper);
            return orders != null ? orders : new ArrayList<>();  // 确保返回一个非空列表
        }

        wrapper.eq(ProductsOrders::getStatus, status);
        wrapper.orderByDesc(ProductsOrders::getCreatedTime);
        List<ProductsOrders> orders = productsOrdersMapper.selectList(wrapper);

        return orders != null ? orders : new ArrayList<>();  // 确保返回一个非空列表
    }


    @Override
    public List<ProductsOrdersDetails> queryOrders(Integer userId, Long id) {
        LambdaQueryWrapper<ProductsOrdersDetails> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductsOrdersDetails::getProductsOrdersId, id);
        List<ProductsOrdersDetails> orders = productsOrdersDetailsMapper.selectList(wrapper);
        return orders;

    }

    @Override
    public void cancelOrder(Long orderId, Integer userId) {
        LambdaQueryWrapper<ProductsOrders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductsOrders::getId, orderId);
        wrapper.eq(ProductsOrders::getUserId, userId);
        ProductsOrders productsOrders = productsOrdersMapper.selectOne(wrapper);
        if (productsOrders != null) {
            productsOrders.setStatus(3);
            productsOrdersMapper.updateById(productsOrders);
        }

    }

    @Override
    public String pay(Long orderId, String uniqueCode) {
        log.info("获取到的参数是：{}, {}", orderId, uniqueCode);

        // 通过 id 查询订单
        ProductsOrders productsOrders = productsOrdersMapper.selectById(orderId);
        if (productsOrders == null) {
            throw new RuntimeException("订单不存在");
        }
        productsOrdersMapper.updateById(productsOrders);

        // 创建交易页面的支付请求对象
        AlipayTradePagePayRequest request = getAlipayTradePagePayRequest(productsOrders);
        String form;
        try {
            // 调用 SDK 生成表单
            form = alipayClient.pageExecute(request).getBody();
            log.info("支付宝支付表单：" + form);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }

        // 修改状态为 2
        productsOrders.setStatus(2);
        productsOrdersMapper.updateById(productsOrders);
        return form;
    }



    @Override
    @Transactional
    public void updateStatus(Long orderId, Integer orderStatus) {
        ProductsOrders order = productsOrdersMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在，ID：" + orderId);
        }
        order.setStatus(2);
        productsOrdersMapper.updateById(order);
        log.info("修改订单状态成功");
        Products products = productsMapper.selectById(order.getProductId());
        if(products.getSeatCount()==1){
            productsMapper.delete(new LambdaQueryWrapper<Products>().eq(Products::getProductId,order.getProductId()));
            log.info("修改车辆库存成功");
            return;
        }
        products.setSeatCount(products.getSeatCount() - 1);
        productsMapper.updateById(products);
        log.info("修改车辆库存成功");
    }


    private AlipayTradePagePayRequest getAlipayTradePagePayRequest(ProductsOrders productsOrders) {
        log.info("获取到订单：{}",productsOrders);
        //1.准备支付的参数，包括需要支付的订单的id，价格，物品名称
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(productsOrders.getId().toString()); // 需要支付的订单id，自定义的订单id，不能重复，唯一，已经支付的无法继续支付
        model.setTotalAmount(productsOrders.getPrice().toString()); // 需要支付的钱 model.setTotalAmount("88.88");
        model.setSubject("配置车辆"); // 要支付的物品，比如 model.setSubject("Iphone6 16G");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");  //销售产品码，电脑支付场景就使用FAST_INSTANT_TRADE_PAY

        // 2.创建支付的请求，设置上面的准备支付的参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setBizModel(model);

        // 3.设置支付宝异步回调，这个需要用内网穿透
        request.setNotifyUrl(alipayConfig.getNotifyUrl());

        // 4.设置支付宝支付成功返回的页面，这里让支付成功直接回到static下的一个静态页面中
        request.setReturnUrl(alipayConfig.getReturnUrl());
        return request;
    }

}




